package com.example.kotlintest.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.example.kotlintest.bean.TouTiaoData
import com.example.kotlintest.net.DataRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import java.net.UnknownHostException
import javax.inject.Inject

@HiltViewModel
class DataViewModel @Inject constructor(
    private val repository: DataRepository
) : ViewModel() {


    fun weatherData(cityname: String, key: String) = liveData {
        try {
            emit(repository.getWeatherData(cityname, key))
        } catch (e: UnknownHostException) {
            emit(e.toString())
        }
    }

    fun toutiaoData(): Flow<PagingData<TouTiaoData.Result.Data>> {
        return repository.getToutiaoData().cachedIn(viewModelScope)
    }
}